package com.kdd.campus.sh.service.impl;

import com.kdd.campus.sh.dao.ShAddressMapper;
import com.kdd.campus.sh.po.ShAddress;
import com.kdd.campus.sh.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @Auther: fcp
 * @Date: 2020/4/27 21:52
 * @Description:
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private ShAddressMapper addressMapper;

    @Override
    public List<ShAddress> findByUserId(Long userId) {
        Example example = new Example(ShAddress.class);
        example.setOrderByClause("is_default desc");
        example.and().andEqualTo("userId",userId);
        return addressMapper.selectByExample(example);
    }

    @Transactional
    @Override
    public void update(ShAddress address) {
        if (address.getIsDefault()==1){
            // 如果将当前地址设为默认地址，取消之前设置的默认地址
            Example example = new Example(ShAddress.class);
            example.and().andEqualTo("userId", address.getUserId()).andEqualTo("isDefault",1);
            addressMapper.updateByExampleSelective(ShAddress.builder().isDefault(0).build(),example);
        }

        Example example = new Example(ShAddress.class);
        example.createCriteria()
                .andEqualTo("id",address.getId())
                .andEqualTo("userId", address.getUserId());
        addressMapper.updateByExampleSelective(address,example);
    }

    @Override
    public void add(ShAddress address) {
        if (address.getIsDefault()==1){
            // 如果将当前地址设为默认地址，取消之前设置的默认地址
            Example example = new Example(ShAddress.class);
            example.and().andEqualTo("userId", address.getUserId()).andEqualTo("isDefault",1);
            addressMapper.updateByExampleSelective(ShAddress.builder().isDefault(0).build(),example);
        }

        address.setCreateTime(new Date());
        addressMapper.insert(address);
    }

    @Override
    public void delete(Long userId, Integer id) {
        addressMapper.delete(ShAddress.builder().userId(userId).id(id).build());
    }

    @Override
    public ShAddress findDefaultAddress(Long userId) {
        return addressMapper.selectOne(ShAddress.builder().userId(userId).isDefault(1).build());
    }

    @Override
    public ShAddress findAddressById(Long userId, Integer addressId) {
        ShAddress address = addressMapper.selectOne(ShAddress.builder().id(addressId).userId(userId).build());
        return address;
    }
}
